/*
 * Created on 2005-10-31
 * Last modified on 2006-12-18
 * Powered by YeQiangWei.com
 */
 package com.yeqiangwei.tools;

import com.yeqiangwei.util.TypeChange;

public class EncodeIP{
	
	public static void main(String args[]){
		EncodeIP e = new EncodeIP();
		System.out.println(e.enAddr("192.168.1.1"));
		
	}
	
    private String reqIp = "";
    
    public void setReqIp(String reqIp) {
        this.reqIp = reqIp;
    }
    
    public long enIpAddr(String ip){
    	long l = 0;
    	ip = this.enAddr(ip); 
    	l = TypeChange.stringToLong(ip);
    	return l;
    }
    
    
    public long deIpAddr(String ip){
    	long l = 0;
    	ip = this.deAddr(ip); 
    	l = TypeChange.stringToLong(ip);
    	return l;
    }
    
    public String enAddr(String ip){
        if(ip==null||ip.equals("")){
            if(reqIp==null || reqIp.equals("")){
                ip = "127.0.0.1";
            }else{
                ip = reqIp;
            }
        }
        String esip, str1, str2, str3, str4;
        long int1, int2, int3, int4;
        int i = ip.indexOf("."); //取小数点第一次出现的位置
        str1 = ip.substring(0,i); //截取字符串指定长度substring 相当于vb的Mid函数。
        // 分别取出Ip各段字符串，然后转化成Integer类型
        esip = ip.substring(i+1);
        i = esip.indexOf(".");
        str2 = esip.substring(0,i);
        esip = esip.substring(i+1); //截取字符串长度从i+1到字符串尾
        i = esip.indexOf(".");
        str3 = esip.substring(0,i);  
        i = esip.indexOf(".");
        str4 = esip.substring(i+1);  
        int1 = Integer.parseInt(str1);
        int1 = Long.parseLong(str1);
        int2 = Long.parseLong(str2);
        int3 = Long.parseLong(str3);        
        int4 = Long.parseLong(str4); 
        /*
        System.out.println(str1);
        System.out.println(str2);
        System.out.println(str3);
        System.out.println(str4);
        */
        return String.valueOf((int1 * 256 * 256 * 256) + (int2 * 256 * 256) + (int3 * 256) + int4 - 1);
    }
    
    public String deAddr(String ip){
        if(ip==null||ip.equals("")){
            ip = reqIp;
        }
        if(ip==null||ip.equals("")){
            return "127.0.0.1";
        }
        long sip;
        sip = Long.parseLong(ip);
        long s1, s21, s2, s31, s3, s4;
        String temp;
        sip = sip + 1;
        s1 = sip / 256 / 256 / 256;
        s21 = s1 * 256 * 256 * 256;
        s2 = (sip - s21) / 256 / 256;
        s31 = s2 * 256 * 256 + s21;
        s3 = (sip - s31) / 256;
        s4 = sip - (s3 * 256) - s31;
        temp = String.valueOf(s1) + "." + String.valueOf(s2) + "." + String.valueOf(s3) + "." + String.valueOf(s4);
        return temp;
    }
    
    
}
